package com.quasar.hpatient.view.record;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.Typeface;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.quasar.hpatient.MainAppliaction;
import com.quasar.hpatient.R;
import com.quasar.hpatient.base.BaseActivity;
import com.quasar.hpatient.constant.ConstantManger;
import com.quasar.hpatient.model.custommodel.OutJionValueDataBean;
import com.quasar.hpatient.model.custommodel.TemperatureTableItem;
import com.quasar.hpatient.model.httpmodel.AnotherResult;
import com.quasar.hpatient.model.httpmodel.DataStateResult;
import com.quasar.hpatient.model.medicalmodel.DailyRecordDetailsData;
import com.quasar.hpatient.onInterface.OndailyRecordListener;
import com.quasar.hpatient.presenter.DailyRecordPresenter;
import com.quasar.hpatient.utils.DateUtil;
import com.quasar.hpatient.utils.OutliersValues;
import com.quasar.hpatient.utils.TimeZoneUtil;
import com.quasar.hpatient.view.adapter.IntakeOutputAdapter;
import com.quasar.hpatient.widget.SeekBarEditWidget;
import com.quasar.hpatient.widget.WidgetDateAdd;
import com.quasar.hpatient.widget.WidgetTime;
import com.quasar.hpatient.widget.lineChartView;
import com.rey.material.app.Dialog;
import com.rey.material.app.DialogFragment;
import com.rey.material.app.SimpleDialog;
import com.vise.log.ViseLog;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.OptionsItem;
import org.androidannotations.annotations.OptionsMenu;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TreeMap;

import lecho.lib.hellocharts.gesture.ZoomType;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Column;
import lecho.lib.hellocharts.model.ColumnChartData;
import lecho.lib.hellocharts.model.SubcolumnValue;
import lecho.lib.hellocharts.view.ColumnChartView;

/**
 * 出入量
 */
@OptionsMenu(R.menu.menu_preservation)
@EActivity(R.layout.activity_intake_output)
public class IntakeOutputActivity extends BaseActivity implements OndailyRecordListener {

    private IntakeOutputAdapter intakeOutputAdapter;
    private DailyRecordPresenter dailyRecordPresenter;

    @ViewById(R.id.rv_list)
    RecyclerView rv_list;
    @ViewById(R.id.main_toolbar)
    Toolbar main_toolbar;
    @ViewById(R.id.lc_post_list)
    lineChartView lc_post_list;
    @ViewById(R.id.wd_dataAdd)
    WidgetDateAdd wd_dataAdd;
    //出量
    @ViewById(R.id.sw_out)
    SeekBarEditWidget sw_out;
    //入量
    @ViewById(R.id.sw_in)
    SeekBarEditWidget sw_in;
    //时分
    @ViewById(R.id.wt_time)
    WidgetTime wt_time;
    @Extra
    String TimeVal;//其他跳转过来的时间

    @AfterViews
    void init() {
        initView();
        initData();
        initToolbar();
    }

    @Override
    protected void initView() {
        initToolbar();
        rv_list.setLayoutManager(new LinearLayoutManager(this));
        rv_list.setHasFixedSize(true);
        rv_list.setNestedScrollingEnabled(false);
        //隐藏日期按钮
        wd_dataAdd.hideViewDate();
        if (TimeVal != null && TimeVal.length() > 0) {
            wd_dataAdd.setTimeDate(TimeVal);
        }


        sw_out.onClickTextView(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edittText(null,"出量");
            }
        });

        sw_in.onClickTextView(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edittText(null,"入量");
            }
        });
    }

    @Override
    protected void initData() {
        dailyRecordPresenter = new DailyRecordPresenter(this);
        initDataView();

    }

    //保存
    @OptionsItem(R.id.action_preservation)
    public void action_preservation() {

        //出量
        final String out_high = sw_out.getDetectVal();
        //入量
        final String in_low = sw_in.getDetectVal();

        //时分
        String timeMin = wt_time.getTime();
        //日期
        String DateTime = wd_dataAdd.getDataTime();

        final StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(DateTime);
        stringBuffer.append(" " + timeMin + ":00");


        String markValue = "";
        if (sw_out.CbChoice()) {
            markValue = "夜尿量";
        }

        //出入量全为正常
        String warn = "0";


        if (Integer.parseInt(out_high) > 0 || Integer.parseInt(in_low) > 0) {
            showDialog();
            if (Integer.parseInt(out_high) > 0 && Integer.parseInt(in_low) > 0) {
                for (int i = 0; i < 2; i++) {
                    if (i == 0) {
                        dailyRecordPresenter.AddDailyRecordDetailData(
                                out_high,
                                stringBuffer.toString(),//出量
                                markValue,
                                "0",//入量
                                ConstantManger.INOUTPUTVAL,
                                ConstantManger.INOUTPUTVALUNIT, warn);
                    } else {
                        dailyRecordPresenter.AddDailyRecordDetailData(
                                "0",
                                stringBuffer.toString(),//出量
                                "",
                                in_low,//入量
                                ConstantManger.INOUTPUTVAL,
                                ConstantManger.INOUTPUTVALUNIT, warn);
                    }
                }
            } else {
                if (Integer.parseInt(out_high) > 0) {
                    dailyRecordPresenter.AddDailyRecordDetailData(
                            out_high,
                            stringBuffer.toString(),//出量
                            markValue,
                            "0",//入量
                            ConstantManger.INOUTPUTVAL,
                            ConstantManger.INOUTPUTVALUNIT, warn);
                } else if (Integer.parseInt(in_low) > 0) {
                    dailyRecordPresenter.AddDailyRecordDetailData(
                            "0",
                            stringBuffer.toString(),//出量
                            "",
                            in_low,//入量
                            ConstantManger.INOUTPUTVAL,
                            ConstantManger.INOUTPUTVALUNIT, warn);
                }
            }
        } else {
            msg("请选择数值");
        }
    }

    @Override
    public void onDailyRecordDetailsSuccess(AnotherResult<DailyRecordDetailsData> data) {
        List<TemperatureTableItem> temperatureTableItemList = new ArrayList<>();
        if (data.getList().size() != 0) {
            a.clear();
            y.clear();
            y1.clear();
            y2.clear();
        } else {
            a.clear();
            y.clear();
            y1.clear();
            y2.clear();
        }


        for (int i = 0; i < data.getList().size(); i++) {

            TemperatureTableItem temperatureTableItem = new TemperatureTableItem();
            temperatureTableItem.setId(data.getList().get(i).getId() + "");
            temperatureTableItem.setLogTime(data.getList().get(i).getLogTime());
            temperatureTableItem.setLogValue(data.getList().get(i).getLogValue());
            temperatureTableItem.setPaired(data.getList().get(i).getPaired());
            temperatureTableItem.setItemType(data.getList().get(i).getLogType());
            temperatureTableItem.setDailyitemDose(data.getList().get(i).getDailyitemDose());
            if (data.getList().get(i).getMarkValue() != null && data.getList().get(i).getMarkValue().length() > 0) {
                temperatureTableItem.setMarkValues(data.getList().get(i).getMarkValue());
            }
            if (Float.parseFloat(data.getList().get(i).getLogValue()) > 0) {
                temperatureTableItem.setDailyitemName("出量");
            } else {
                temperatureTableItem.setDailyitemName("入量");
            }
            temperatureTableItem.setItemType(TemperatureTableItem.BODY);
            temperatureTableItem.setStats(0 + "");//2代表正常
            temperatureTableItem.setReferenceValue(ConstantManger.BLOODPRESSUREFERENCEHIGH);//参考值
            temperatureTableItemList.add(temperatureTableItem);

        }

//        lc_post_list.setFlashback(temperatureTableItemList);

        initAdapter(temperatureTableItemList);

        Map<String, String> map = new TreeMap<>(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.compareTo(o2);
            }
        });

        for (int i = 0; i < temperatureTableItemList.size(); i++) {
            if (temperatureTableItemList.get(i).getLogTime() != null && temperatureTableItemList.get(i).getLogTime().length() > 0) {
                map.put(temperatureTableItemList.get(i).getLogTime().substring(0, 10), temperatureTableItemList.get(i).getLogTime());
            }
        }

        for (String time : map.keySet()) {
            int outSum = 0;
            int inSum = 0;
            int isnight = 0;
            for (int i = 0; i < temperatureTableItemList.size(); i++) {
                if (temperatureTableItemList.get(i).getLogTime() != null && temperatureTableItemList.get(i).getLogTime().length() > 0) {
                    if (temperatureTableItemList.get(i).getLogTime().substring(0, 10).equals(time)) {
                        if (data.getList().get(i).getMarkValue().equals("夜尿量")) {
                            isnight = isnight + Integer.parseInt(data.getList().get(i).getLogValue());
                        }

                        try {
                            outSum = outSum + Integer.parseInt(data.getList().get(i).getLogValue());
                            inSum = inSum + Integer.parseInt(data.getList().get(i).getPaired());
                        }catch (Exception e){

                        }
                    }
                }
            }

            y.add(outSum + "");
            y1.add(inSum + "");
            y2.add(isnight + "");
            a.add(time);
        }
        initcolumn(a, y, y1, y2);
        dessDialog();
    }

    //初始化adapter布局
    private View errorView;

    public void initAdapter(List<TemperatureTableItem> data) {
        intakeOutputAdapter = new IntakeOutputAdapter(data);
        //添加头布局
        if (data.size() > 0) {
            errorView = getLayoutInflater().inflate(R.layout.widget_test_show, (ViewGroup) rv_list.getParent(), false);
            TextView title= (TextView) errorView.findViewById(R.id.title);
            title.setText("时间");
            TextView msg= (TextView) errorView.findViewById(R.id.msg);
            msg.setText("项目");
            TextView msgcheck= (TextView) errorView.findViewById(R.id.msgcheck);
            msgcheck.setText("毫升(ml)");
            intakeOutputAdapter.addHeaderView(errorView);
        }
        rv_list.setAdapter(intakeOutputAdapter);

        intakeOutputAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {


//                    case R.id.msg:
                    case R.id.msgcheck://出量
                        String tableItem = intakeOutputAdapter.getData().get(position).dailyitemName;
                        if (intakeOutputAdapter.getData().get(position).getStats() != null && intakeOutputAdapter.getData().get(position).getDailyitemName() != null) {
                            if (!tableItem.contains("总")) {
                                TemperatureTableItem temperatureTableItem = intakeOutputAdapter.getData().get(position);
                                edittText(temperatureTableItem,"");
                            }
                        }
                        break;
                }
            }
        });

        intakeOutputAdapter.setOnItemChildLongClickListener(new BaseQuickAdapter.OnItemChildLongClickListener() {
            @Override
            public boolean onItemChildLongClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
//                    case R.id.msg:
                    case R.id.msgcheck:
                        String tableItem = intakeOutputAdapter.getData().get(position).dailyitemName;
                        if (intakeOutputAdapter.getData().get(position).getStats() != null && intakeOutputAdapter.getData().get(position).getDailyitemName() != null) {
                            if (!tableItem.contains("总")) {
                                TemperatureTableItem temperatureTableItem = intakeOutputAdapter.getData().get(position);
                                dialogdelete(temperatureTableItem);
                            }
                        }
                        break;
                }
                return true;
            }
        });
    }

    public void dialogdelete(final TemperatureTableItem temperatureTableItem) {

        Dialog.Builder builder = new SimpleDialog.Builder(R.style.SimpleDialogLight) {
            @Override
            public void onPositiveActionClicked(DialogFragment fragment) {
                super.onPositiveActionClicked(fragment);
                deleteLongClick(temperatureTableItem.getId());
            }

            @Override
            public void onNegativeActionClicked(DialogFragment fragment) {
                super.onNegativeActionClicked(fragment);
            }
        };
        builder.title("确认删除检测项吗？")
                .positiveAction("确定")
                .negativeAction("取消");
        ((SimpleDialog.Builder) builder).message("检测值可以帮助医生更准确的了解你的情况");
        DialogFragment fragment = DialogFragment.newInstance(builder);

        if (this instanceof AppCompatActivity) {
            AppCompatActivity activity = this;
            fragment.show(activity.getSupportFragmentManager(), null);
        }
    }

    public void deleteLongClick(String itemId) {
        dailyRecordPresenter.updateAloneItemDailyRecordDetail(itemId, "", "", "", ConstantManger.DELETEDAILY, "", "");
    }

    public void edittText(final TemperatureTableItem temperatureTableItem, final String str) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("请输检测值");
        View views = LayoutInflater.from(this).inflate(R.layout.dialog_edit_detection, null, false);
        builder.setView(views);


        //收缩压
        final EditText edit_min = (EditText) views.findViewById(R.id.edit_detection);
        edit_min.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_NORMAL);
        edit_min.setFilters(new InputFilter[]{new InputFilter.LengthFilter(4)});
        edit_min.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                edit_min.setSelection(s.length());
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

                if (s.toString() != null && s.toString().length() > 0) {
                    if (OutliersValues.editTextNum(s.toString())) {
                        TextColer(edit_min, 1);
                    }
                }

                if (s.toString().trim().substring(0).equals(".")) {
                    edit_min.setText("0" + s);
                    edit_min.setSelection(2);
                }

            }
        });

        StringBuffer stringBuffer=new StringBuffer();
        if(temperatureTableItem!=null){
            if (Integer.parseInt(temperatureTableItem.getPaired()) > 0) {
                edit_min.setText(temperatureTableItem.getPaired());
            } else {
                edit_min.setText(temperatureTableItem.getLogValue());
            }
            stringBuffer.append("确定");
        }else{
            stringBuffer.append("提交");
        }


        builder.setPositiveButton(stringBuffer.toString(), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String valmin = edit_min.getText().toString();
                if (valmin.length() == 0 || valmin==null) {
                    msg("检测值不能为空");
                    return;
                }

                String markVal = "";

                if(temperatureTableItem!=null){
                    if (temperatureTableItem.getMarkValues() != null && temperatureTableItem.getMarkValues().length() > 0) {
                        if (temperatureTableItem.getMarkValues().equals("夜尿量")) {
                            markVal = temperatureTableItem.getMarkValues();
                        }
                    }

                    if (Integer.parseInt(temperatureTableItem.getPaired()) > 0) {
                        dailyRecordPresenter.updateAloneItemDailyRecordDetail(temperatureTableItem.getId() + "", "0", valmin, "", ConstantManger.UPDATEDAILY, "", "");
                    } else {
                        dailyRecordPresenter.updateAloneItemDailyRecordDetail(temperatureTableItem.getId() + "", valmin, "0", markVal, ConstantManger.UPDATEDAILY, "", "");
                    }
                }else{
                    if(str.equals("出量")){
                        sw_out.EditTextView(valmin);
                    }else{
                        sw_in.EditTextView(valmin);
                    }
                    action_preservation();
                }
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                showKeyboard(edit_min);
            }
        }, 300);

        builder.show();

    }

    public void showKeyboard(EditText editText) {
        if (editText != null) {
            //设置可获得焦点
            editText.setFocusable(true);
            editText.setFocusableInTouchMode(true);
            //请求获得焦点
            editText.requestFocus();
            //调用系统输入法
            InputMethodManager inputManager = (InputMethodManager) editText
                    .getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.showSoftInput(editText, 0);
        }
    }

    private int color(int value) {
        return MainAppliaction.getInstance().getResources().getColor(value);
    }

    public void TextColer(EditText textView, int color) {
        if (color == 1 || color == 2) {
            textView.setTextColor(color(R.color.btcolor));
        } else {
            textView.setTextColor(color(R.color.red));
        }
    }


    @Override
    public void onError(String msg) {
        if (msg != null) {
            msg(msg);
        }
        dessDialog();
    }

    @Override
    public void onRefreshUI() {
        dessDialog();
    }

    @Override
    public void onSubmitSuccess(DataStateResult dataStateResult) {

        if (dataStateResult.getMsgCode().equals("0x00000000")) {
            //获取显示的日期
            msg("操作成功");
            initDataView();
            sw_out.SeekBardefault();
            sw_in.SeekBardefault();
            sw_out.EditCheckBox();
            sw_out.EditTextView(0+"");
            sw_in.EditTextView(0+"");
        }
        dessDialog();
    }

    public void initDataView() {
        final String type = "7";//获取一周时间
        String Time = wd_dataAdd.getDataTime();
        dailyRecordPresenter.GetUserOneDayDailyRecordData(ConstantManger.INOUTPUTVAL, Time, type);
    }

    @Override
    public void onUpdateValueSuccess(DataStateResult dataStateResult) {
        initDataView();
    }

    @Override
    public void onDeleteValueSuccess(DataStateResult dataStateResult) {
        initDataView();
    }


    //初始化柱状图
    List<String> a = new ArrayList<>();  //X轴的标注
    List<String> y = new ArrayList<>();//图表的数据
    List<String> y1 = new ArrayList<>();//图表的数据
    List<String> y2 = new ArrayList<>();//图表的数据
    //柱状图
    @ViewById(R.id.column_chart)
    ColumnChartView column_chart;

    public void initcolumn(List<String> a, List<String> y, List<String> y1, List<String> y2) {
        //一个柱状图需要一个柱子集合
        List<Column> columnList = new ArrayList<>();
        //每根柱子又可以分为多根柱子
        List<SubcolumnValue> subcolumnValueList;
        int columns = a.size();//一共7根柱子   //时间长度
        int subColumn = 1;//每根柱子的子柱子为1根
        for (int i = 0; i < columns; i++) {
            subcolumnValueList = new ArrayList<>();
            for (int j = 0; j < subColumn; j++) {
                subcolumnValueList.add(new SubcolumnValue(Float.parseFloat(y.get(i)), Color.parseColor("#01B786")));
                subcolumnValueList.add(new SubcolumnValue(Float.parseFloat(y2.get(i)), Color.parseColor("#4A8A00")));
                subcolumnValueList.add(new SubcolumnValue(Float.parseFloat(y1.get(i)), Color.parseColor("#FFC125")));
            }
            //每根柱子需要一个子柱子集合
            Column column = new Column(subcolumnValueList);
            column.setHasLabels(true);//是否直接显示标注（其它的一些设置类似折线图）
            columnList.add(column);
        }
        ColumnChartData data = new ColumnChartData(columnList);
        Axis axisX = new Axis();
        axisX.setTextColor(Color.parseColor("#000000"));// 灰色
        axisX.setTextSize(11);// 设置字体大小
        axisX.setMaxLabelChars(7); // 最多几个X轴坐标，意思就是你的缩放让X轴上数据的个数7<=x<=mAxisValues.length
        Axis axisY = new Axis().setHasLines(true);
        axisY.hasLines();//是否显示网格线
        axisY.setTextColor(Color.BLACK);//颜色
        //给轴设置值
        axisY.setTextSize(9);// 设置字体大小
        axisY.setTextColor(Color.parseColor("#000000"));
        data.setAxisXBottom(axisX);  //显示X轴
        data.setAxisYLeft(axisY);  //显示Y轴
        data.setValueLabelTypeface(Typeface.MONOSPACE);// 设置数据文字样式
        List<AxisValue> list = new ArrayList<>();
        for (int i = 0; i < a.size(); i++) {
            list.add(new AxisValue(i).setLabel(a.get(i).substring(5, 10)));//i代表位置，label则是在轴上该位置的标注
        }
        //给x轴设置值
        axisX.setValues(list);
        data.setAxisXBottom(axisX);
        //设置是否让多根子柱子在同一根柱子上显示（会以断层的形式分开），由于这里子柱子只有一根，故设置true也无意义，读者可自行尝试
        data.setStacked(false);
        data.setValueLabelBackgroundColor(Color.parseColor("#161718"));
        data.setValueLabelBackgroundEnabled(false);
        data.setValueLabelsTextColor(Color.parseColor("#161718"));
        data.setFillRatio(0.7f);//设置柱子之间的间距
        column_chart.setZoomType(ZoomType.HORIZONTAL);
//        column_chart.setMaxZoom((float) 5);// 缩放比例
        column_chart.setZoomEnabled(true);
        column_chart.setColumnChartData(data);

    }
}
